package org.jprobe;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.jprobe.utils.XmlUtils;
import org.w3c.dom.NodeList;
/**
*
* Workspace implementation
*
* @author Hussain Al-Mutawa
* @version 1.0
*/
public class Workspace extends AbstractWorkspace {
	/**
	 * workspace file absolute path
	 */
	private transient String path;
	/**
	 * list of projects directories in the workspace
	 */
	private transient List<String>projects;

	@Override
	public void setPath(final String path) {
		this.path=path.replace('\\', '/');
		this.projects=new LinkedList<String>();
		final File[]files=new File(path).listFiles();
		for(final File file:files){
			if(isProject(file) && isEclipseJavaProject(file.getAbsolutePath())){
				this.projects.add(file.getName());
			}
			//System.out.println(file);
		}
	}

	@Override
	public String getPath() {
		return path;
	}

	@Override
	public String[] getProjects() {
		return projects.toArray(new String[projects.size()]);
	}

	/**
	 * determines if the project is:<br/>
	 * 1. java project.<br/>
	 * 2. created by eclipse IDE
	 * @param project the project directory full path to be tested if a valid java project
	 * @return true if passed the two tests, false otherwise
	 * @throws JProbeRuntimeException if the path to the project is invalid
	 */
	public static boolean isEclipseJavaProject(final String project){

		try {
			final File file = new File(project);
			if(file.exists()==false){
				throw new JProbeException("directory {"+project+"} can not be found");
			}
			final List<String>list=Arrays.asList(file.list());
			boolean result = list.contains(".classpath") & list.contains(".project");
			final NodeList nodeList = XmlUtils.xpath(project+"/.project", "//projectDescription/buildSpec/buildCommand/name/text()");
			result &= nodeList.getLength()>0 && nodeList.item(0).getNodeValue().toString().equals("org.eclipse.jdt.core.javabuilder");
			return result;
		} catch (final JProbeException exp) {
			throw new JProbeRuntimeException(exp);
		}

	}
}
